<?php

namespace app\api\controller;

use app\admin\controller\Servec;
use app\admin\model\Banner;
use app\admin\model\Text;
use app\common\controller\Api;
use app\common\model\Coupon;
use app\common\model\HotCity;
use app\common\model\Inform;
use app\common\model\InviteLog;
use app\common\model\OrderServe;
use app\common\model\Question;
use app\common\model\SearchLog;
use app\common\model\Technician;
use app\common\model\TechnicianServe;
use app\common\model\UseCoupon;
use app\common\model\Withdraw;
use Exception;
use PDOException;
use think\Db;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['question','getTime','inform','vicinity','banner','serve_list','servec','questionDetail','timing','text','hotCity','getTimelist'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     *
     */
    public function index()
    {
        $this->success('请求成功');
    }

    /**
     * 首页附近技师
     * param lat 纬度
     * param lon 经度
     * param city 城市
     */
    public function vicinity(){

      $lon=$this->request->request('lon');
      $lat=$this->request->request('lat');
      $city=$this->request->request('city');
      if($city){
    $where['service_area']=['like',"$city"];
      }
      $info = [];
      $technician_list = \app\common\model\Technician::where($where)->
       field('technician_id,technician_avatar,lon,lat')->select();
      if($technician_list){
        foreach ($technician_list as $key=>$value){
          if ($value['lat'] == 0 || $value['lon'] == 0) {
            $distance = '999km';
          } else {
            $distance = distance($value['lon'],$value['lat'],$lon,$lat);
          }

          $info[]=[
            'technician_id'     => $value['technician_id'],
            'technician_avatar' => $value['technician_avatar'],
            'distance'          => $distance,
            'lon'              =>$value['lon'],
            'lat'               => $value['lat'],
          ];
        }
        if ($lon != 0 && $lat != 0) {
          array_multisort(array_column($info,'distance'),SORT_ASC,$info);
        }
        $this->success('查询成功',$info);
      }
    }



    /**
     * 首页服务列表
     */

    public function serve_list(){
        $page=$this->request->request('page',1);
        $serve_cid=$this->request->request('serve_cid');
        $serve=Db::name('serve')->where(['serve_status'=>1,'is_added'=>0,'serve_cid'=>$serve_cid])->field('id,serve_name,serve_image,serve_price')->page($page,6)->select();
        $this->success('查询成功',$serve);
    }


  /**
   * 首页服务分类
   */

  public function servec(){
    $page=$this->request->request('page',1);
    $servec=\app\admin\model\store\Servec::page($page,8)->select();
    $this->success('查询成功',$servec);
  }


    /**
     * 帮助中心（常见问题）
     */

    public function question(){
        $list=Question::field('id,title')->order('weigh','desc')->page($this->request->request('page',1),10)->select();;
        $this->success('查询成功',$list ?? []);
    }

    /**
     * 常见问题详情
     */
    public function questionDetail(){
        $id = $this->request->request('id');
        if(!$id){
            $this->error('参数不能为空!');
        }
        $data = Question::get($id);
        $this->success('查询成功',$data ?? []);
    }

    /**
     * 注销账户
     * 伪删除，做一个判断
     */

    public function logoff(){
        $uid=$this->auth->id;
      $postion=$this->request->request('postion');//用户身份 1用户 2 技师
        $user=\app\common\model\User::where(['id'=>$uid,'del_flag'=>0])->find();
        if(!$user){
            $this->error('当前账号已注销');
        }
        //检查订单
       $order=\app\common\model\Order::where(['uid'=>$uid,'order_status'=>2])->select();
       if(!empty($order)){
           $this->error('当前用户有待服务的订单，暂不能注销账户');
       }
      $check_withdraw=Withdraw::where(['user_id'=>$uid,'status'=>'created'])->find();
      if($check_withdraw)
        $this->error('您有正在处理中的提现申请，请在提现申请理完成后进行注销');

      $res=\app\common\model\User::where(['id'=>$uid,'postion'=>$postion])->update(['del_flag'=>1,'mobile'=>'']);
      if($postion==2){
        $te=\app\common\model\Technician::where(['uid'=>$uid])->find();
        if($te->store_id!=0){
          $this->error('当前账号已加入店铺,暂不支持注销账户');
        }
        //检查订单
        $order=\app\common\model\Order::where(['technician_id'=>$te->technician_id,'order_status'=>2])->select();
        if(!empty($order)){
          $this->error('当前技师有待服务的订单，暂不能注销账户');
        }
        TechnicianServe::where(['technician_id'=>['in',$te->technician_id]])->update(['technician_id'=>0]);
        $te->delete();
      }
      $this->auth->logout();
       if($res){
           $this->success('注销成功');
       }else{
           $this->error('注销失败');
       }
    }

    /**
     * 文本管理
     *
     */
    public function text()
    {
        $id   = $this->request->request('id');
        $text = Text::where('id', $id)->find();
        $this->success('', $text);
    }

    /**
     * 举报类型管理
     */

    public function inform(){

        $inform=Db::name('inform')->select();
        $this->success('查询成功',$inform);
    }

    /**
     * 根据地址选择城市
     *  address  地址
     */

    public function  getCity(){

      $address=$this->request->request('address');
      if(!$address){
        $this->error('地址不能为空');
      }
      $list=Db::name('area')->where(['name'=>['like',"%$address%"]])->select();
      $this->success('查询成功',$list??[]);
    }

    /**
     * 城市列表
     */

    public function CityList(){
        $list=Db::name('area')->where('level','=','2')->order('first','asc')->select();
        $this->success('查询成功',$list??[]);
    }


    /**
     * 热门城市
     */

    public function  hotCity(){

      $list=HotCity::all();

      $this->success('查询成功',$list??[]);
    }



    /**
     * 首页搜索
     * type 1 技师搜索 2 服务搜索
     */

    public function search(){
      $uid=$this->auth->id;
     $name=$this->request->request('name');
      $type=$this->request->request('type');
      $store_id=$this->request->request('store_id',0);
      if(!$name){
          $this->error('参数不能为空');
      }
      if($store_id){
          if($type==1){
              $log=\app\common\model\Technician::where(['technician_name'=>['like',"% $name%"],'store_id'=>['in',$store_id]])->field('technician_id,technician_name,technician_address,technician_age,technician_gender,technician_avatar,real_name,introduction,is_check')->select();
          }else if($type==2){
              $serve_ids=TechnicianServe::where('store_id','in',$store_id)->group('store_id')->column('store_id');
              $log=\app\common\model\Serve::where(['serve_name'=>['like',"%$name",'store_id'=>['in',$serve_ids]],'serve_status'=>1])->field('id,serve_name,serve_image,serve_duration,serve_price,sales,time_label,feedback,star,serve_details')->select();
          }
      }else{
          if($type==1){
              $log=\app\common\model\Technician::where(['technician_name'=>['like',"% $name%"]])->select();
              foreach ($log as $item){
                  $item['store']=\app\common\model\Store::where(['store_id'=>$item['store_id']])->field('store_id,name')->find();
              }
          }else if($type==2){
              $log=\app\common\model\Serve::where(['serve_name'=>['like',"%$name%"],'serve_status'=>1,'is_added'=>0])->field('id,serve_name,serve_image,serve_duration,serve_price,sales,time_label,feedback,star,serve_details')->select();
              foreach ($log as $key=>$value){
                  $logs=TechnicianServe::where(['serve_id'=>['in',$value['id'],'status'=>1]])->group('store_id')->column('store_id');
                  $value['store']=\app\common\model\Store::where(['store_id'=>['in',$logs]])->field('store_id,name')->find();
              }
          }
      }
      $data=[
        'uid'=>$uid,
        'type'=>$type,
         'is_clear'=>1,
        'search_name'=>$name,
        'createtime'=>time(),
          'store_id'=>$store_id
      ];
      $res=SearchLog::create($data);
      SearchLog::where('id',$res->id)->setInc('search_count',1);//搜素量加1
      $this->success('查询成功',$log);
    }




    /**
     * 清空搜索历史
     */

    public function clearSearch(){

      $uid=$this->auth->id;
        $store_id=$this->request->request('store_id',0);
        if($store_id!=0){
            $res=SearchLog::where(['uid'=>$uid,'store_id'=>$store_id])->update(['is_clear'=>2]);
        }else{
            $res=SearchLog::where(['uid'=>$uid])->update(['is_clear'=>2]);
        }
      if($res){
        $this->success('清空成功');
      }else{
        $this->error('清空失败');
      }
    }


    /**
     * 历史搜索
     */

    public function SearchHistory(){
      $uid=$this->auth->id;
      $store_id=$this->request->request('store_id',0);
      if($store_id!=0){
          $search=SearchLog::where(['uid'=>$uid,'store_id'=>$store_id])->field('search_name')->order('search_count','desc')->select();
      }else{
          $search=SearchLog::where(['uid'=>$uid,'is_clear'=>1])->field('search_name')->select();
      }
      $this->success('',$search);
    }


    /**
     * 热门搜索
     */

    public function hotySearch(){

      $uid=$this->auth->id;
        $store_id=$this->request->request('store_id',0);
       if($store_id!=0){
           $search=SearchLog::where(['uid'=>$uid,'is_clear'=>1,'store_id'=>$store_id])->field('search_name')->order('search_count','desc')->select();
       }else{
           $search=SearchLog::where(['uid'=>$uid])->field('search_name')->order('search_count','desc')->select();
       }
      $this->success('',$search);
    }

  /**
   * 下单时间列表
   *
   */
  public function getTimelist()
  {
      $id = $this->request->request('id');
      $technician    = Technician::where('technician_id', $id)->find();
      if(!$technician)
          $this->error('技师不存在');

      $start = (int)$technician['serve_time'];
      $end = (int)$technician['serve_time_end'];
      $onetime = mktime($start, 0, 0, date("m"), date("d"), date("y"));
      $twotime = mktime($end, 0, 0, date("m"), date("d"), date("y"));
      $ttime = mktime($end, 0, 0, date("m"), date("d") + 2, date("y"));
      $where['book_start_time'] = ['<=', $ttime];
      $where['book_end_time'] = ['>=', $onetime];
      $where['technician_id'] = $id;
      $where['order_status'] = ['in', [1, 2, 3, 4, 5]];
      $res = \app\admin\model\Order::where($where)
          ->select() ?: [];
      $arr = [];
      $dayArr = [];
      for ($j = 0; $j < 3; $j++) {
          $day = datetime(time() + (24 * 3600 * $j), "Y-m-d");
          for ($i = 0; $i < 48; $i++) {
              if ($j == 0) {
                  $beginTime = mktime(0, 0, 0, date("m"), date("d"), date("y"));
                  if (intval(datetime(time(), "H")) * 2 + 2 <= $i) {
                      // 0 营业； 1 ：不在工作时间内；2 已预约
                      $end = $beginTime + ($i * 1800);

                      if ($end < $twotime && $onetime <= $end) {
                          if (count($res) > 0) {
                              //if(in_array($end,$app_time))
                              if (timeInTime($res, $end))
                                  $arr[0][] = ['date' => datetime($end, "H:i"),
                                      'status' => 1];
                              else
                                  $arr[0][] = ['date' => datetime($end, "H:i"),
                                      'status' => 0];
                          } else
                              $arr[0][] = ['date' => datetime($end, "H:i"),
                                  'status' => 0];
                      } else
                          $arr[0][] = ['date' => datetime($end, "H:i"),
                              'status' => 1];
                  } else
                      continue;
              } else {
                  $beginTime = mktime(0, 0, 0, date("m"), date("d") + $j, date("y"));
                  $end = $beginTime + ($i * 1800);
                  if ($end < $twotime + $j * 3600 * 24 && $onetime + $j * 3600 * 24 <= $end) {
                      if (count($res) > 0) {
                          //if(in_array($end,$app_time))
                          if (timeInTime($res, $end))
                              $arr[$j][$i] = ['date' => datetime($end, "H:i"),
                                  'status' => 1];
                          else
                              $arr[$j][$i] = ['date' => datetime($end, "H:i"),
                                  'status' => 0];
                      } else
                          $arr[$j][$i] = ['date' => datetime($end, "H:i"),
                              'status' => 0];
                  } else
                      $arr[$j][$i] = ['date' => datetime($end, "H:i"),
                          'status' => 1];
              }
          }
          $dayArr[$j] = $day;
      }
      $this->success(__('获取成功'), [$dayArr, $arr]);

  }


    /**
     * 下单时间列表
     */
  public function getTime(){

      $arr    = [];
      $dayArr = [];
//      $h=date('H');
      for($j = 0; $j < 3; $j++){
          $day = datetime(time() + (24 * 3600 * $j), "Y-m-d");
          for($i = 0; $i < 48; $i++){
              if($j == 0){
                  $beginTime = mktime(0, 0, 0, date("m"), date("d"), date("y"));
                  if(intval(datetime(time(), "H")) * 2<= $i){
                      $b     = $beginTime + ($i * 1800);
                      $times = $b - time();
                      if($times < 1800){
                          $b = $b + 3600;
                      }
                      $c=datetime($b,'H');
                      if($c>=8 && $c<=20)
                          $arr[0][] = ['date' => datetime($b, "H:i"),
                              'status' => 1];
                      else
                          $arr[0][] = ['date' => datetime($b, "H:i"),
                              'status' => 2];
                  }else{
                      continue;
                  }
              }else{
                  $beginTime   = mktime(0, 0, 0, date("m"), date("d") + $j, date("y"));
                  $b           = $beginTime + ($i * 1800);
                  $c=datetime($b,'H');
                  if($c>=8 && $c<=20)
                      $arr[0][] = ['date' => datetime($b, "H:i"),
                          'status' => 1];
                  else
                      $arr[0][] = ['date' => datetime($b, "H:i"),
                          'status' => 2];
//                  $arr[$j][$i] = datetime($b, "H:i");
              }
          }
          $dayArr[$j] = $day;
      }
      $this->success(__('获取成功'), [$dayArr, $arr]);
  }


  /**
   * banner
   */

  public function banner(){

    $id=$this->request->request('id');
    $banner=Banner::where(['id'=>$id])->find();
    $this->success('查询成功',$banner);
  }

    public function bannerlist(){

        $banner=Banner::all();
        $this->success('查询成功',$banner);
    }


  /**
   * 定时任务 优惠券时间
   */
    public function timing(){
        //优惠券到期
        $couponlist=UseCoupon::where('expiration_time','<',time())->select();
        $coupon=Coupon::where('end_time','<',time())->select();
        if($couponlist){
            foreach($couponlist as $v){
                $v['status'] = 3;
                $v->save();
            }
        }
        if($coupon){
            foreach($coupon as $k){
                $k['status'] = 3;
                $k->save();
            }
        }
      //未支付订单取消订单
      $order_list = \app\common\model\Order::where(['order_status' => 0])->select();
      foreach($order_list as $value){
        $times=config('site.countdown');
        if((time() - $value['createtime']) > $times * 60){
          $value['order_status'] = 11;
          $value->save();
        }
      }
      $this->success('成功');
    }
}
